<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>spring boot + websocket广播式</title>
</head>
<body onload="disconnect();">
<noscript>
    <h2 style="color: #ff0000;">貌似你的浏览器不支持websocket</h2>
</noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>

    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name"/>
        <button id="sendName" onclick="sendName();">发送</button>
        <p id="response"></p>
    </div>
</div>

<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery-3.2.1.min.js}"></script>

<script type="text/javascript">
    var stompClient = null;
    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility=connected?'visible':'hidden';
        $('#response').html();
    }

    function connect() {
        //连接SockJS的endpoint名称为/endpointWisely
        var socket = new SockJS('/endpointWisely');
        //使用STOMP子协议的WebSocket客户端
        stompClient = Stomp.over(socket);
        //连接WebSocket服务端
        stompClient.connect({},function (frame) {
            setConnected(true);
            console.log('Connected: '+frame);
            //通过stompClient.subscribe订阅/topic/getResponse目标（destination）发送的消息，
            //这个是在控制器的@SendTo中定义的
            stompClient.subscribe('/topic/getResponse',function (responsse) {
                //返回的数据是一个对象需要通过body属性获取返回的数据json对象
                console.log("the response is :"+responsse.body);
                showResponse(JSON.parse(responsse.body).responseMessage);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = $('#name').val();
        //通过stompClient.send向/welcome目标（destination）发送消息，这个是在控制器的
        //@MesssageMapping中定义的
        stompClient.send("/welcome",{},JSON.stringify({'name':name}));
    }

    function showResponse(message) {
        var response = $('#response');
        response.html(message);
    }

</script>


</body>
</html>